/**
 * @Project: Runer
 * @Title: ActivtyHome.java
 * @Package com.runlooker.runer.other
 * @author town
 * @date 2014-5-21 下午8:34:05
 * @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
 * @version V1.0
 */
package com.runlooker.runer.ui.home;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.dao.ChatMsgDao;
import com.runlooker.runer.dao.DbUtil;
import com.runlooker.runer.dao.PersonInfoDao;
import com.runlooker.runer.dao.PresenceDao;
import com.runlooker.runer.dao.RosterEntryDao;
import com.runlooker.runer.entity.LocalRosterEntity;
import com.runlooker.runer.entity.PersonInfoEntity;
import com.runlooker.runer.interfaces.IConnectionStatusListener;
import com.runlooker.runer.interfaces.RosterChangeListener;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseFragmentActivity;
import com.runlooker.runer.ui.home.contact.ContactFragment;
import com.runlooker.runer.ui.home.discover.DiscoverFragment;
import com.runlooker.runer.ui.home.message.MessageFragment;
import com.runlooker.runer.ui.login.LoginActivity;
import com.runlooker.runer.ui.personInfo.MyInfoActivity;
import com.runlooker.runer.ui.searchPerson.SearchPersonActivity;
import com.runlooker.runer.util.NetworkUtil;
import com.runlooker.runer.util.PreferenceUtils;
import com.runlooker.runer.util.T;

/**
 * @ClassName ActivtyHome
 * @Description 模块描述
 * @author town
 * @Date 2014-5-21
 */
public class HomeActivty extends BaseFragmentActivity implements
		IConnectionStatusListener, OnClickListener, OnItemClickListener {
	private static final String tag = HomeActivty.class.getSimpleName();
	private static final int LOGOUT_ACTION = 0;// 注销操作
	private static final int AUTO_LOGIN_FAILED = 1;// 自动登录失败
	private static final int INIT_SUCCESS = 2;// 初始化成功
	private static final int INIT_FAILED = 3;// 初始化失败

	private FragmentPagerAdapter mAdapter;
	private ViewPager mViewPager;
	private XmppService mXmppService;

	private MessageFragment mMessageFragment;
	private DiscoverFragment mDiscoverFragment;
	private ContactFragment mContactFragment;
	private ListPopupWindow mMenuWindow;
	private TextView mNotConnectedTagTV;
	// private View mAttachView;
	private ImageView mTabLine;
	private ImageView mSearch;
	private ImageView mMenu;
	private MenuAdapter mMenuAdapter;
	private List<Fragment> mFragments = new ArrayList<Fragment>();
	private List<String> mMenuNameList = new LinkedList<String>();
	private int currentIndex;
	private int screenWidth;
	private List<RosterChangeListener> mRosterChangeCallbacklist = new LinkedList<RosterChangeListener>();

	private PersonInfoDao mPersonInfoDao;
	private RosterEntryDao mRosterEntryDao;
	private DbUtil mDbUtil;

	private boolean isAutoLogout = false;// 是否主动退出

	private Thread mInitDataThread;
	private Thread mLoginThread;

	public void registerRosterChangeCallback(RosterChangeListener rc) {
		mRosterChangeCallbacklist.add(rc);
	}

	public void removeRosterChangeCallback(RosterChangeListener rc) {
		mRosterChangeCallbacklist.remove(rc);
	}

	public void clearAllRosterChangeCallback() {
		mRosterChangeCallbacklist.clear();
	}

	ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppService = ((XmppService.XMPPBinder) service).getService();
			if (!(mXmppService.isLogin())) {
				mNotConnectedTagTV.setText("未连接服务器");
				mNotConnectedTagTV.setVisibility(View.VISIBLE);
			} else {
				initDataThread();
			}

		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mXmppService = null;
		}
	};

	public XmppService getService() {
		return mXmppService;
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case INIT_SUCCESS:// 初始化成功
				hideCustomProgressDialog();
				mNotConnectedTagTV.setVisibility(View.GONE);
				mXmppService.rosterChange();
				// mXmppService.
				break;
			case INIT_FAILED:// 初始化失败
				hideCustomProgressDialog();
				mNotConnectedTagTV.setText("初始化失败");
				mNotConnectedTagTV.setVisibility(View.VISIBLE);
				T.showLong(HomeActivty.this, "初始化失败！");
				break;
			case LOGOUT_ACTION:
				mXmppService.clearDataBase();
				Intent intent = new Intent(HomeActivty.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
				break;
			case AUTO_LOGIN_FAILED:
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		initialize();

	}

	private void logoutAction() {
		isAutoLogout = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					mDbUtil.clearDataBase();
					mXmppService.logout();
				} catch (XMPPException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(LOGOUT_ACTION);
			}
		}).start();
	}

	/**
	 * @Title: initialize
	 * @Description: 方法描述
	 */
	private void initialize() {

		Intent intent = new Intent(HomeActivty.this, XmppService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		mDbUtil = new DbUtil(this);
		mPersonInfoDao = new PersonInfoDao(this);
		mRosterEntryDao = new RosterEntryDao(this);

		mSearch = (ImageView) findViewById(R.id.iv_home_search_btn);
		mMenu = (ImageView) findViewById(R.id.iv_home_menu_btn);
		mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
		mNotConnectedTagTV = (TextView) findViewById(R.id.not_connected_tag);
		// mAttachView = findViewById(R.id.home_pop_attach);

		mSearch.setOnClickListener(this);
		mMenu.setOnClickListener(this);
		mNotConnectedTagTV.setOnClickListener(this);

		mMessageFragment = new MessageFragment();
		mDiscoverFragment = new DiscoverFragment();
		mContactFragment = new ContactFragment();

		mFragments.add(mMessageFragment);
		mFragments.add(mDiscoverFragment);
		mFragments.add(mContactFragment);

		/**
		 * 初始化Adapter
		 */
		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() {
				return mFragments.size();
			}

			@Override
			public Fragment getItem(int arg0) {
				return mFragments.get(arg0);
			}
		};
		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(0);

		initTabLine();
		initEvent();
	}

	private void initEvent() {

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				currentIndex = position;
			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {
				/**
				 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
				 * 然后改变根据positionOffset动态改变TabLine的leftMargin
				 */
				if (currentIndex == 0 && position == 0)// 0->1
				{
					LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
							.getLayoutParams();
					lp.leftMargin = (int) (positionOffset
							* (screenWidth * 1.0 / 3) + currentIndex
							* (screenWidth / 3));
					mTabLine.setLayoutParams(lp);

				} else if (currentIndex == 1 && position == 0) // 1->0
				{
					LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
							.getLayoutParams();
					lp.leftMargin = (int) (-(1 - positionOffset)
							* (screenWidth * 1.0 / 3) + currentIndex
							* (screenWidth / 3));
					mTabLine.setLayoutParams(lp);

				} else if (currentIndex == 1 && position == 1) // 1->2
				{
					LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
							.getLayoutParams();
					lp.leftMargin = (int) (positionOffset
							* (screenWidth * 1.0 / 3) + currentIndex
							* (screenWidth / 3));
					mTabLine.setLayoutParams(lp);
				} else if (currentIndex == 2 && position == 1) // 2->1
				{
					LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
							.getLayoutParams();
					lp.leftMargin = (int) (-(1 - positionOffset)
							* (screenWidth * 1.0 / 3) + currentIndex
							* (screenWidth / 3));
					mTabLine.setLayoutParams(lp);
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
	}

	/**
	 * 获得初始化数据的线程（如果未登录则先登录）
	 */
	private void initDataThread() {
		if (NetworkUtil.getNetworkState(this) != NetworkUtil.NETWORN_NONE
				&& mXmppService.isLogin()) {
			if (mInitDataThread == null) {
				showCustomProgrssDialog("初始化...");
				mInitDataThread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							updateUserAndPhoneInfo();
							updateRoster();
							mHandler.sendEmptyMessage(INIT_SUCCESS);
						} catch (Exception e) {
							e.printStackTrace();
							mHandler.sendEmptyMessage(INIT_FAILED);
						} finally {
							if (mInitDataThread != null) {
								synchronized (mInitDataThread) {
									mInitDataThread = null;
								}
							}
						}
					}
				});
				mInitDataThread.start();
			}
		}
	}

	/**
	 * 获得个人信息、然后将本地手机信息和个人信息存储到服务器
	 * 
	 * @throws XMPPException
	 */
	private void updateUserAndPhoneInfo() throws XMPPException {
		PersonInfoEntity myInfo = new PersonInfoEntity();
		myInfo = mXmppService.getOurPersonInfo();
		if (myInfo != null) {
			mXmppService.savePersonInfo(myInfo);
			mPersonInfoDao.saveOrUpdatePersonInfo(myInfo);
		}
	}

	private void closePopup() {
		if (mMenuWindow != null && mMenuWindow.isShowing()) {
			mMenuWindow.dismiss();
		}
	}

	private void showPopup() {
		initMenuBtnName();
		if (mMenuWindow != null) {
			mMenuWindow.dismiss();
			mMenuWindow = null;
		}
		mMenuWindow = new ListPopupWindow(this);
		if (mMenuAdapter == null) {
			mMenuAdapter = new MenuAdapter(this);
		}
		mMenuAdapter.setData(mMenuNameList);
		mMenuWindow.setModal(true);
		mMenuWindow.setContentWidth(getResources().getDimensionPixelSize(
				R.dimen.popo_menu_dialog_width));
		mMenuWindow.setAdapter(mMenuAdapter);
		mMenuWindow.setOnItemClickListener(this);
		mMenuWindow.setAnchorView(mMenu);
		if (mMenuWindow != null && !mMenuWindow.isShowing()) {
			mMenuWindow.show();
		}
		mMenuWindow.getListView().setDividerHeight(1);
	}

	private void initMenuBtnName() {
		mMenuNameList = new LinkedList<String>();
		String account = PreferenceUtils.getPrefString(this,
				MyApplication.ACCOUNT_USERNAME_KEY, "");
		mMenuNameList.add(account);
		mMenuNameList.add("设置");
		mMenuNameList.add("我的收藏");
		mMenuNameList.add("我的参与");
		mMenuNameList.add("退出帐号");
		mMenuNameList.add("关于");
		mMenuNameList.add("反馈");
	}

	/**
	 * 获得花名册
	 */
	private void updateRoster() {
		Collection<RosterEntry> Entries = mXmppService.getEntities();
		mRosterEntryDao.clearTable();
		if (Entries != null && !Entries.isEmpty()) {
			Iterator<RosterEntry> iterator = Entries.iterator();
			while (iterator.hasNext()) {
				LocalRosterEntity roster = LocalRosterEntity
						.entryToEntity(iterator.next());
				mRosterEntryDao.saveOrUpdateRosterEntry(roster);
			}
		}
	}

	/**
	 * 根据屏幕的宽度，初始化引导线的宽度
	 */
	private void initTabLine() {
		mTabLine = (ImageView) findViewById(R.id.id_tab_line);
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindow().getWindowManager().getDefaultDisplay()
				.getMetrics(outMetrics);
		screenWidth = outMetrics.widthPixels;
		LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
				.getLayoutParams();
		lp.width = screenWidth / 3;
		mTabLine.setLayoutParams(lp);
	}

	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		if (connectedState == XmppService.CONNECTED) {
			initDataThread();
		} else {
			if (!(connectedState == XmppService.CONNECTED)) {
				if (isAutoLogout) {
					mNotConnectedTagTV.setVisibility(View.GONE);
				} else {
					mNotConnectedTagTV.setText("未连接服务器");
					mNotConnectedTagTV.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		clearAllRosterChangeCallback();
		unbindService(mConnection);
		mHandler.removeCallbacksAndMessages(null);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.not_connected_tag:
			if (!(NetworkUtil.getNetworkState(this) == NetworkUtil.NETWORN_NONE)) {
				if (mLoginThread == null) {
					mLoginThread = new Thread(new Runnable() {
						public void run() {
							try {
								mXmppService.login();
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								synchronized (mLoginThread) {
									mLoginThread = null;
								}
							}
						}
					});
					mLoginThread.start();
				}
			} else {
				T.showLong(HomeActivty.this, "请检查网络！");
			}

			break;
		case R.id.iv_home_menu_btn:
			mMenu.post(new Runnable() {
				@Override
				public void run() {
					showPopup();
				}
			});
			break;
		case R.id.iv_home_search_btn:
			Intent intent = new Intent(this, SearchPersonActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	public void add(View view) {
		Intent intent = new Intent(this, SearchPersonActivity.class);
		startActivity(intent);
	}

	class MenuAdapter extends BaseAdapter {
		List<String> menuName;
		private LayoutInflater mLayoutInflater;

		public MenuAdapter(Context context) {
			mLayoutInflater = LayoutInflater.from(context);
		}

		public void setData(List<String> menuName) {
			this.menuName = menuName;
		}

		@Override
		public int getCount() {
			return menuName.size();
		}

		@Override
		public Object getItem(int position) {
			return menuName.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.menu_listitem_layout, null);
			}
			TextView tv = (TextView) convertView
					.findViewById(R.id.tv_menu_listitem);
			tv.setText(menuName.get(position));
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mMenu.post(new Runnable() {
			@Override
			public void run() {
				closePopup();
			}
		});
		switch (position) {
		case 0:// 角色信息

			Intent intent = new Intent(HomeActivty.this, MyInfoActivity.class);
			intent.putExtra("account", PreferenceUtils.getPrefString(
					HomeActivty.this, MyApplication.ACCOUNT_USERNAME_KEY, ""));
			startActivity(intent);
			break;
		case 1:// 设置

			break;
		case 2:// 我的收藏

			break;
		case 3:// 我的参与

			break;
		case 4:// 退出帐号

			logoutAction();
			break;
		case 5:// 关于

			break;
		case 6:// 反馈

			break;
		default:
			break;
		}
	}

}
